package com.bjpowernode.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.bjpowernode.mapper.TClueMapper;
import com.bjpowernode.entity.query.ClueExcel;
import lombok.extern.slf4j.Slf4j;
import java.util.List;

@Slf4j
public class ClueExcelListener implements ReadListener<ClueExcel> {

    private final TClueMapper  clueMapper;

    // 每100条存储数据库，然后清理list ，方便内存回收
    private static final int BATCH_COUNT = 100;

    //缓存的数据
    private List<ClueExcel> list = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    public ClueExcelListener (TClueMapper clueMapper) {
        this.clueMapper = clueMapper;
    }


    /**
     * 这个每一条数据解析都会来调用
     * @param clueExcel
     * @param analysisContext
     */
    @Override
    public void invoke(ClueExcel clueExcel, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", clueExcel);
        list.add(clueExcel);
        if (list.size() >= BATCH_COUNT){
            saveData();
            list = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成！");
    }

    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        clueMapper.importExcel(list);
        log.info("存储数据库成功！");
    }
}
